package com.xunshibao.core.page;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageUtils {
	private static final String SELECT_REG = "select(.*?)from";
	private static Pattern SELECT_PTN = Pattern.compile(SELECT_REG);
	public static String convertPageSQL(String sql) {
		Matcher matcher = SELECT_PTN.matcher(sql);
		if (matcher.find()) {
			String cols = matcher.group(1);
			sql = sql.replace(cols, " count(*) ");
			int orderIndex = sql.indexOf("order by");
			if(orderIndex != -1) {
				sql = sql.substring(0, orderIndex);
			}
			return sql;
		}
		return null;
	}
	
	public static String genPageSQL(String sql, int start, int pageSize) {
		StringBuilder sqlBuffer = new StringBuilder(sql);
		sqlBuffer.append(" limit ");
		sqlBuffer.append(start);
		sqlBuffer.append(",");
		sqlBuffer.append(pageSize);
		return sqlBuffer.toString();
	}
	
	
	
//	public static void main(String[] args) {
//		String pageSQL = PageUtils.genPageSQL("select * from table", 0, 10);
//		System.out.println(pageSQL);
//	}
}
